<?php

declare(strict_types=1);

namespace app\middleware;

use app\common\facade\auth\Auth;
use app\model\AgentChannel;
use app\model\AgentServiceConfig;
use think\facade\Db;
use think\facade\Log;

/**
 * 获取渠道配置
 */
class ApiChannel
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     *
     * @return Response
     */
    public function handle($request, \Closure $next)
    {

        Log::info('h5接口请求域名'.request()->url().'token:'.$request->header('Authorization'));
        Log::info('h5接口请求数据'.json_encode(request()->all(),JSON_UNESCAPED_UNICODE));

        //todo 虚拟渠道，不去验证，用于总后台调试使用
//        if (input('channel') == AgentChannel::YMHC_ADMIN_CHANNEL) {
//            return $next($request);
//        }
        $agentChannel = Auth::attemptChannel();

        if (empty($agentChannel)) {
            return fail('渠道不存在');
        }
        if ($agentChannel['state'] != 1) {
            return fail('渠道已禁用');
        }
        $templateStatus = Db::name('template')
            ->where('id', $agentChannel['template_id'])
            ->value('status');
        if ($templateStatus != 1) {
            return fail('模板已禁用');
        }

        // 代理商是否已经被禁用
        $agent = Db::name('agent')
            ->field('id, status, settle_type')
            ->where('id', $agentChannel['agent_id'])
            ->find();
        if (empty($agent) || $agent['status'] != 1) {
            return fail('通道维护中.');
        }
        $agentChannel['settle_type'] = $agent['settle_type'];

        $servType = $request->servType;
        if ($servType) {
            $agentServiceConfig = Db::name('agent_service_config')
                ->where('agent_id', $agent['id'])
                ->where('serv_type', $servType)
                ->where('status', 1)
                ->whereNull('deleted_at')
                ->find();
            if (empty($agentServiceConfig)) {
//                【'.$request->servName.'】
                return fail('尚未开通产品权限');
            }
            // 判断有效期
            if (in_array($servType, [PRODUCT_OIL_SERV, PRODUCT_MEAL_SERV, PRODUCT_METUAN_SERV,PRODUCT_MEITUAN_TAKEOUT_SERV,PRODUCT_SECKILL_SERV,PRODUCT_ELE_SERV]) && $agentServiceConfig['time_end'] < time() && $agentServiceConfig['income_type'] == AgentServiceConfig::INCOME_TYPE_SELF) {
                return fail('【'.$request->servName.'】产品权限已经到期，请及时续费');
            }
        }

        $request->agentChannel = $agentChannel;


        return $next($request);
    }
}
